package com.gogowan.agroenterprise.storage;

import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.gogowan.agroenterprise.MyApplication;
import com.gogowan.agroenterprise.R;
import com.gogowan.agroenterprise.contorl.MyAsyncTask;
import com.gogowan.agroenterprise.model.LoginResultInfo;
import com.gogowan.agroenterprise.model.ResultInfo;
import com.gogowan.agroenterprise.model.StoreListResult;
import com.gogowan.agroenterprise.model.StoreModel;
import com.gogowan.agroenterprise.model.StoreRequest;
import com.gogowan.agroenterprise.utils.Utils;
import com.gogowan.agroenterprise.widget.SlideListView;
import com.gogowan.agroenterprise.widget.adapter.SlideBaseAdapter;
import com.gogowan.agroenterprise.widget.adapter.SlideViewHolder;

/**
 * 仓库详情界面
 * 
 * @author tjh 2017-01-04
 *
 */
@SuppressLint("NewApi")
public class WarehouseInfoActivity extends Activity implements
		View.OnClickListener {
	private ProgressDialog progressDialog;
	private StoreModel storeModel;
	private List<StoreModel> storeModelList = new ArrayList<StoreModel>();
	private SlideListView lvcountryListView;
	private ListBaseAdapter mListAdapter;
	private TextView ckmcText, ckbmText, xzckmtText, tjhwText;
	private EditText ckmcEdit, ckbnEdit;
	private Button ckbjBtn;
	private int width;
	// 是否修改数据
	private boolean isChange = false;
	// 是否编辑仓库
	private boolean isCKEdit = false;
	private long storeID;
	private Handler myHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			switch (msg.what) {
			case 0:
				mListAdapter.notifyDataSetChanged();
				ckmcText.setText(storeModel.getStoreName());
				ckmcEdit.setText(storeModel.getStoreName());
				ckbmText.setText(storeModel.getStoreCode());
				ckbnEdit.setText(storeModel.getStoreCode());
				break;
			default:
				break;
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_warehouse_info);

		initView();
		initValue();
	}

	/**
	 * 初始化数据
	 */
	private void initValue() {
		WindowManager wm = this.getWindowManager();
		width = wm.getDefaultDisplay().getWidth();
		storeID = this.getIntent().getLongExtra("storeid", 0);
		String storeName = this.getIntent().getStringExtra("storenaem");

		progressDialog = ProgressDialog.show(this,
				getString(R.string.alert_title),
				getString(R.string.alert_message), true, false);

		StoreRequest storeRequest = new StoreRequest();
		// 1企业；2经销商
//		storeRequest.setEnterpriseID(loginResultInfo.getEnterpriseinfo()
//				.getEnterpriseid());
//		storeRequest.setDealerID(loginResultInfo.getEnterpriseinfo()
//				.getDealerId());
//		storeRequest.setUserType(loginResultInfo.getEnterpriseinfo()
//				.getUserType());
		storeRequest.setStoreID(storeID);
		storeRequest.setUserID(MyApplication.mSettings.getLong("personid",0));
		storeRequest.setStoreName(storeName);
		storeRequest.setPageIndex(1);
		storeRequest.setType(1);

		GetWarehouseInfoAsyn getWarehouseInfoAsyn = new GetWarehouseInfoAsyn();
		getWarehouseInfoAsyn.execute(storeRequest);
	}

	/**
	 * 初始化界面
	 */
	private void initView() {
		lvcountryListView = (SlideListView) findViewById(R.id.warehouse_info_lvcountry);
		mListAdapter = new ListBaseAdapter(this, storeModelList,
				R.layout.activity_warehouse_info_item, R.layout.slide_content);
		lvcountryListView.setAdapter(mListAdapter);
		lvcountryListView
				.setOnSlideItemClickListener(new SlideListView.OnSlideItemClickListener() {

					@Override
					public void onItemClick(AdapterView<?> parent, View view,
							int position, long id) {
						// TODO Auto-generated method stub
						String storeModelJson = Utils.toJSON(storeModelList
								.get(position));
						Intent intent = new Intent(WarehouseInfoActivity.this,
								GoodsAllocationInfoActivity.class);
						intent.putExtra("storeModelJson", storeModelJson);
						intent.putExtra("pstoreID", storeID);
						WarehouseInfoActivity.this.startActivityForResult(
								intent, 310);
					}
				});

		ckmcText = (TextView) findViewById(R.id.warehouse_info_ckmc_text);
		ckbmText = (TextView) findViewById(R.id.warehouse_info_ckbme_text);
		ckmcEdit = (EditText) findViewById(R.id.warehouse_info_ckmc_edit);
		ckbnEdit = (EditText) findViewById(R.id.warehouse_info_ckbm_edit);
		xzckmtText = (TextView) findViewById(R.id.warehouse_info_xzckmt_text);
		tjhwText = (TextView) findViewById(R.id.warehouse_info_tjhw_btn);
		ckbjBtn = (Button) findViewById(R.id.warehouse_info_bjck_btn);

		xzckmtText.setOnClickListener(this);
		tjhwText.setOnClickListener(this);
		ckbjBtn.setOnClickListener(this);

		ImageButton backBtn = (ImageButton) findViewById(R.id.warehouse_info_fh_btn);
		backBtn.setOnClickListener(this);
	}

	/**
	 * list Adapter
	 */
	private class ListBaseAdapter extends SlideBaseAdapter<StoreModel> {

		private List<StoreModel> dataList;

		public ListBaseAdapter(Context context, List<StoreModel> dataList,
				int itemLayoutId, int slideLayoutId) {
			super(context, dataList, itemLayoutId, slideLayoutId);
			this.dataList = dataList;
		}

		@Override
		public void convert(SlideViewHolder holder, StoreModel bean,
				int position) {

			TextView hwmcText = holder
					.getView(R.id.warehouse_info_item_hwmc_text);
			TextView hwbmText = holder
					.getView(R.id.warehouse_info_item_hwbm_text);
			TextView xzhwmtText = holder
					.getView(R.id.warehouse_info_item_xzhwmt_text);
			Button deleteButton = holder.getView(R.id.deleteButton);
			deleteButton.setOnClickListener(new ButtonClickListener(position));
			xzhwmtText.setOnClickListener(new ButtonClickListener(position));

			hwmcText.setText(bean.getStoreName());
			hwbmText.setText(bean.getStoreCode());
			holder.getConvertView().setCanLeftSlide(true);

		}

		class ButtonClickListener implements OnClickListener {

			private int position = 0;

			public ButtonClickListener(int position) {
				this.position = position;
			}

			@Override
			public void onClick(View v) {
				switch (v.getId()) {
				case R.id.warehouse_info_item_xzhwmt_text:
					Bitmap ewmBit = Utils.create2DCoderBitmap(
							dataList.get(position).getEwmUrl(), width, width);
					String pathStr = Utils.saveEWMBitmapToFile(
							ewmBit,
							storeModel.getStoreName() + "_"
									+ dataList.get(position).getStoreName()
									+ ".png");
					if (pathStr == "") {
						Toast.makeText(WarehouseInfoActivity.this, "保存失败", Toast.LENGTH_LONG)
								.show();
					} else {
						MediaScannerConnection
								.scanFile(
										WarehouseInfoActivity.this,
										new String[] { pathStr },
										new String[] { "image/jpeg" },
										new MediaScannerConnection.OnScanCompletedListener() {
											@Override
											public void onScanCompleted(
													String path, Uri uri) {
											}
										});
						Toast.makeText(WarehouseInfoActivity.this,
								"保存成功：" + pathStr, Toast.LENGTH_LONG).show();
					}
					break;
				case R.id.deleteButton:
					Toast.makeText(WarehouseInfoActivity.this,
							"单击删除按钮，第" + position + "个", Toast.LENGTH_LONG).show();
					break;
				}
			}
		}
	}

	/**
	 * 获取仓库信息
	 * 
	 * @author tjh
	 *
	 */
	private class GetWarehouseInfoAsyn extends MyAsyncTask {

		@Override
		protected void onPostExecute(Object res) {
			if (res == null || res.equals("")) {
				Toast.makeText(WarehouseInfoActivity.this,
						getString(R.string.server_error), Toast.LENGTH_LONG)
						.show();
			} else {
				com.gogowan.agroenterprise.model.Message message = (com.gogowan.agroenterprise.model.Message) Utils
						.fromJSON((String) res,
								com.gogowan.agroenterprise.model.Message.class);
				String string = Utils.getMessageContent(message);

				if (string == null || string.equals("")) {
					Toast.makeText(WarehouseInfoActivity.this,
							getString(R.string.analyse_error),
							Toast.LENGTH_LONG).show();
				} else {
					StoreListResult storeListResult = (StoreListResult) Utils
							.fromJSON(string, StoreListResult.class);

					if (storeListResult.getResult() == 21500) {
						storeModel = storeListResult.getStore();
						if (storeListResult.getStoreList() != null) {
							storeModelList.clear();
							storeModelList.addAll(storeListResult
									.getStoreList());
							myHandler.sendEmptyMessage(0);
						}
					} else {
						Toast.makeText(WarehouseInfoActivity.this,
								storeListResult.getResultinfo(),
								Toast.LENGTH_LONG).show();
					}
				}
			}
			progressDialog.dismiss();
			super.onPostExecute(res);
		}

		@Override
		protected Object doInBackground(Object... params) {
			StoreRequest storeRequest = (StoreRequest) params[0];
			String json = Utils.toJSON(storeRequest);
			com.gogowan.agroenterprise.model.Message message = new com.gogowan.agroenterprise.model.Message(
					21500, true, json);
			// String ss = Utils.toJSON(message);
			// Log.i("gggggggggggggggggg===", ss);
			String res = Utils.postCommit(getString(R.string.first_url)
					+ getString(R.string.first_url_page), message);
			return res;
		}
	}

	/**
	 * 保存编辑仓库信息
	 * 
	 * @author tjh
	 *
	 */
	private class SaveWarehouseInfoAsyn extends MyAsyncTask {

		@Override
		protected void onPostExecute(Object res) {
			if (res == null || res.equals("")) {
				Toast.makeText(WarehouseInfoActivity.this,
						getString(R.string.server_error), Toast.LENGTH_LONG)
						.show();
			} else {
				com.gogowan.agroenterprise.model.Message message = (com.gogowan.agroenterprise.model.Message) Utils
						.fromJSON((String) res,
								com.gogowan.agroenterprise.model.Message.class);
				String string = Utils.getMessageContent(message);

				if (string == null || string.equals("")) {
					Toast.makeText(WarehouseInfoActivity.this,
							getString(R.string.analyse_error),
							Toast.LENGTH_LONG).show();
				} else {
					ResultInfo resultInfo = (ResultInfo) Utils.fromJSON(string,
							ResultInfo.class);

					if (resultInfo.getResult() == 21200) {
						isChange = true;
						isCKEdit = false;
						ckbjBtn.setText("编辑仓库");
						ckmcText.setText(ckmcEdit.getText());
						ckbmText.setText(ckbnEdit.getText());

						ckmcEdit.setVisibility(View.GONE);
						ckmcText.setVisibility(View.VISIBLE);
						ckbnEdit.setVisibility(View.GONE);
						ckbmText.setVisibility(View.VISIBLE);
					}
					Toast.makeText(WarehouseInfoActivity.this,
							resultInfo.getResultinfo(), Toast.LENGTH_LONG)
							.show();
				}
			}
			progressDialog.dismiss();
			super.onPostExecute(res);
		}

		@Override
		protected Object doInBackground(Object... params) {
			StoreModel storeModel = (StoreModel) params[0];
			String json = Utils.toJSON(storeModel);
			com.gogowan.agroenterprise.model.Message message = new com.gogowan.agroenterprise.model.Message(
					21200, true, json);
			// String ss = Utils.toJSON(message);
			// Log.i("gggggggggggggggggg===", ss);
			String res = Utils.postCommit(getString(R.string.first_url)
					+ getString(R.string.first_url_page), message);
			return res;
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK) {
			switch (requestCode) {
			case 310:
				// 货位信息被修改
				isChange = true;
				initValue();
				break;
			default:
				break;
			}
		}
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.warehouse_info_fh_btn:
			// 返回
			if (isChange) {
				Intent intent = new Intent(this, WarehouseListActivity.class);
				setResult(RESULT_OK, intent);
			}
			this.finish();
			break;
		case R.id.warehouse_info_xzckmt_text:
			// 下载仓库码图
			// 彩色二维码生成
			Bitmap ewmBit = Utils.create2DCoderBitmap(storeModel.getEwmUrl(),
					width, width);
			String pathStr = Utils.saveEWMBitmapToFile(ewmBit,
					storeModel.getStoreName() + ".png");
			if (pathStr == "") {
				Toast.makeText(this, "保存失败", Toast.LENGTH_LONG).show();
			} else {
				MediaScannerConnection.scanFile(this, new String[] { pathStr },
						new String[] { "image/jpeg" },
						new MediaScannerConnection.OnScanCompletedListener() {
							@Override
							public void onScanCompleted(String path, Uri uri) {
							}
						});
				Toast.makeText(this, "保存成功：" + pathStr, Toast.LENGTH_LONG).show();
			}
			break;
		case R.id.warehouse_info_tjhw_btn:
			// 添加货位
			Intent intent = new Intent(this, GoodsAllocationAddActivity.class);
			intent.putExtra("storenaem", storeModel.getStoreName());
			intent.putExtra("storecode", storeModel.getStoreCode());
			intent.putExtra("pstoreID", storeID);
			intent.putExtra("jmrkStr", "info");
			this.startActivityForResult(intent, 310);
			break;
		case R.id.warehouse_info_bjck_btn:
			if (isCKEdit) {
				// 保存仓库信息
				if (TextUtils.isEmpty(ckmcEdit.getText())) {
					Toast.makeText(this, "请输入仓库名称", Toast.LENGTH_LONG).show();
				} else if (TextUtils.isEmpty(ckbnEdit.getText())) {
					Toast.makeText(this, "请输入仓库编码", Toast.LENGTH_LONG).show();
				} else {
					progressDialog = ProgressDialog.show(this,
							getString(R.string.alert_title),
							getString(R.string.alert_message), true, false);



					StoreModel StoreModel2 = new StoreModel();
//					StoreModel2.setEnterprise_Info_ID(loginResultInfo
//							.getEnterpriseinfo().getEnterpriseid());
//					StoreModel2.setDealerID(loginResultInfo.getEnterpriseinfo()
//							.getDealerId());
					StoreModel2.setStoreID(storeID);
					StoreModel2.setStoreName(ckmcEdit.getText() + "");
					StoreModel2.setType(1);
//					StoreModel2.setAddUser(loginResultInfo.getUserinfo()
//							.getPersonid());
					StoreModel2.setStoreCode(ckbnEdit.getText() + "");
//					StoreModel2.setUserType(loginResultInfo.getEnterpriseinfo()
//							.getUserType());

					SaveWarehouseInfoAsyn saveWarehouseInfoAsyn = new SaveWarehouseInfoAsyn();
					saveWarehouseInfoAsyn.execute(StoreModel2);
				}
			} else {
				// 编辑仓库
				isCKEdit = true;
				ckbjBtn.setText("保存");
				ckmcText.setVisibility(View.GONE);
				ckmcEdit.setVisibility(View.VISIBLE);
				ckbmText.setVisibility(View.GONE);
				ckbnEdit.setVisibility(View.VISIBLE);
				ckmcEdit.setSelectAllOnFocus(true);
				ckbnEdit.setSelectAllOnFocus(true);
				ckmcEdit.requestFocus();

				InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
				imm.showSoftInput(ckmcEdit, InputMethodManager.SHOW_FORCED);
			}

			break;
		default:
			break;
		}
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		storeModel = null;
		storeModelList.clear();
		storeModelList = null;
	}
}
